package com.example.auction.activity;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import com.example.auction.R;
import com.example.auction.activity.mineActivity.MineBiddingActivity;
import com.example.auction.sqlite.Sqlite;
import com.example.auction.util.ItemTimeOut;
import com.example.auction.util.MyUtil;
import com.example.auction.util.UserDialog;

public class ItemDetailsViewActivity extends AppCompatActivity {

    private TextView tvBack, tvOwnerName, tvItemName, tvWinnerName,
            tvItemDes, tvMarkupPrice, tvMaxPrice, tvEndTime, tvNewMaxPrice,
            tvPhoneTag, tvPhone;
    private ImageView ivItemImg, ivOwnerImg, ivWinnerImg, ivUserImg;

    private RelativeLayout rl_phone, rl_winner, rlBid, rl_bottom_nav, rlEnterBid;
    private ImageButton ibtnBidAdd, ibtnBidSubtract;

    private LinearLayout llOwner,llOnlyOwner;
    private TextView tvOwnerInitPrice;
    private TextView tvOwnerAddTime;
    private TextView tvOwnerEndTime;

    private Integer winner_id = 0;
    private Integer user_id = 0;
    private Integer owner_id = 0;
    private Integer item_id;
    private Integer markupPrice = 0;

    Sqlite sqlite = new Sqlite(ItemDetailsViewActivity.this);
    private Cursor cursor;
    //加价信标，大于0时才可以进行减价
    private int bidding;
    private Cursor cursor1;
    private TextView tvFrontMaxPrice;
    private LinearLayout ll_maxp_and_end;
    private TextView tv_state;
    private RelativeLayout rl_remark;
    private TextView tv_no_pass_remark;
    private ImageButton ibtn_publish_again;
    private ScrollView sc_content;
    private String from;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_item_details_view);

        //刷新物品状态
        ItemTimeOut.checkItem(this);

        findViewBy();
        initData();
        showItem();
        bidBtns();

    }

    //加价减价拍下按钮监听
    @SuppressLint("Range")
    private void bidBtns() {
        //获取当前拍卖品的加价幅度
        bidding = 0;
        //返回
        tvBack.setOnClickListener(new bidding());
        //加价按钮
        ibtnBidAdd.setOnClickListener(new bidding());
        //减价按钮
        ibtnBidSubtract.setOnClickListener(new bidding());
        //提交竞价
        rlEnterBid.setOnClickListener(new bidding());
        //重新发布
        ibtn_publish_again.setOnClickListener(new bidding());

    }

    //加减价按钮监听
    @SuppressLint("Range")
    private class bidding implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            //获取当前最高价
            Integer maxPrice = Integer.parseInt(
                    tvMaxPrice.getText().toString().trim());
            Integer newMaxPrice = Integer.parseInt(
                    tvNewMaxPrice.getText().toString().trim());

            switch (v.getId()) {
                //返回按钮
                case R.id.tv_back:
                    ItemDetailsViewActivity.this.finish();
                    break;
                //重新发布按钮
                case R.id.ibtn_publish_again:
                    Intent intent = new Intent(ItemDetailsViewActivity.this, AgainAddItemActivity.class);
                    intent.putExtra("user_id", user_id);
                    intent.putExtra("item_id", item_id);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    ItemDetailsViewActivity.this.startActivity(intent);
                    break;
                //加价按钮
                case R.id.ibtn_bid_add:
                    if ((newMaxPrice + markupPrice > maxPrice * 20)
                            || (newMaxPrice + markupPrice > 99999)
                            || bidding >= 20) {
                        Toast.makeText(ItemDetailsViewActivity.this,
                                "请不要恶意加价！", Toast.LENGTH_SHORT).show();
                        ibtnBidSubtract.setBackgroundResource(R.drawable.shape_gray_deep);
                    } else {
                        newMaxPrice += markupPrice;
                        tvNewMaxPrice.setText(newMaxPrice.toString());
                        bidding++;
                        ibtnBidSubtract.setBackgroundResource(R.drawable.shape_white);
                    }
                    break;
                //减价按钮
                case R.id.ibtn_bid_subtract:
                    //至少加价一次才可以点减价
                    if (bidding >= 1) {
                        newMaxPrice -= markupPrice;
                        tvNewMaxPrice.setText(newMaxPrice.toString());
                        bidding--;
                        if (bidding == 0 || (newMaxPrice == maxPrice)) {
                            //减价到等于原价时，按钮变暗
                            ibtnBidSubtract.setBackgroundResource(R.drawable.shape_gray_deep);
                        }
                    }
                    break;
                case R.id.rl_enter_bid:
                    if (bidding < 1) {
                        Toast.makeText(ItemDetailsViewActivity.this,
                                "你还没有出价哦~", Toast.LENGTH_SHORT).show();
                    } else {
                        if (cursor != null && cursor.moveToFirst()) {
                            Integer owner_id = cursor.getInt(cursor.getColumnIndex("owner_id"));
                            if (user_id == owner_id) {
                                Toast.makeText(ItemDetailsViewActivity.this,
                                        "不能竞拍自己的物品！", Toast.LENGTH_SHORT).show();
                            } else {
                                String max_price = tvNewMaxPrice.getText().toString().trim();
                                //更新winner_id = user_id
                                long m = sqlite.updateItem(item_id, "winner_id", user_id.toString());
                                //更新最高价
                                long n = sqlite.updateItem(item_id, "max_price", max_price);

                                //插入或更新竞价表
                                long i = 0;
                                Cursor cursorBid = sqlite.selectBid(item_id, user_id);
                                if (cursorBid != null && cursorBid.moveToFirst()) {
                                    //之前已经对该物品出价过则更新
                                    i = sqlite.updateBid(item_id, user_id, "bid_price", max_price);
                                    i += sqlite.updateBid(item_id, user_id, "bid_date", MyUtil.getNowDateString());
                                } else {
                                    //之前没有对该物品出价过则插入
                                    i = sqlite.insertBid(item_id, user_id, max_price, 0, MyUtil.getNowDateString()) + 1;
                                }
                                if (m > 0 && n > 0 && i > 1) {
                                    Toast.makeText(ItemDetailsViewActivity.this,
                                            "出价成功！", Toast.LENGTH_SHORT).show();
                                    setResult(100);
                                    finish();
                                } else {
                                    Toast.makeText(ItemDetailsViewActivity.this,
                                            "出价失败！" + m + n + i, Toast.LENGTH_SHORT).show();
                                }
                            }

                        }
                    }
                    break;
                default:
                    break;
            }
        }
    }

    @SuppressLint("Range")
    private void showItem() {
        if (cursor != null && cursor.moveToFirst()) {
            owner_id = cursor.getInt(cursor.getColumnIndex("owner_id"));
            winner_id = cursor.getInt(cursor.getColumnIndex("winner_id"));

            //获取拍卖品名称
            String item_name = cursor.getString(cursor.getColumnIndex("item_name"));
            tvItemName.setText(item_name);
            //获取发布者名字
            String owner_name = MyUtil.getUserNameByID(ItemDetailsViewActivity.this, owner_id);
            tvOwnerName.setText(owner_name);

            //获取拍卖品描述
            String item_desc = cursor.getString(cursor.getColumnIndex("item_desc"));
            tvItemDes.setText(item_desc);

            //根据id获取图片
            //拍卖品图片
            Bitmap itemBm = MyUtil.getImageBySQL(ItemDetailsViewActivity.this, "item", item_id);
            ivItemImg.setImageBitmap(itemBm);

            //发布者头像
            Bitmap ownerBm = MyUtil.getImageBySQL(ItemDetailsViewActivity.this, "user", owner_id);
            ivOwnerImg.setImageBitmap(ownerBm);
            ivUserImg.setImageBitmap(ownerBm);

            //最高价者头像
            Bitmap winnerBm = MyUtil.getImageBySQL(ItemDetailsViewActivity.this, "user", winner_id);
            ivWinnerImg.setImageBitmap(winnerBm);

            if (winner_id != 0) {
                //获取最高价者名字
                String winner_name = MyUtil.getUserNameByID(ItemDetailsViewActivity.this, winner_id);
                tvWinnerName.setText(winner_name);
            } else {
                ivWinnerImg.setVisibility(View.VISIBLE);
                tvWinnerName.setText("暂无人出价");
            }

            //加价幅度
            String markup_price = cursor.getString(cursor.getColumnIndex("markup_price"));
            tvMarkupPrice.setText(markup_price);
            markupPrice = Integer.parseInt(markup_price);
            //发布价
            String init_price = cursor.getString(cursor.getColumnIndex("init_price"));
            tvOwnerInitPrice.setText(init_price);
            //最高价
            String max_price = cursor.getString(cursor.getColumnIndex("max_price"));
            tvMaxPrice.setText(max_price);
            tvNewMaxPrice.setText(max_price);

            //发布者手机
            if (from.equals("我买到的")){
                ivUserImg.setImageBitmap(ownerBm);
                tvPhoneTag.setText("卖家手机");
                String owner_phone = MyUtil.getUserPhoneByID(ItemDetailsViewActivity.this, owner_id);
                tvPhone.setText(owner_phone);
            }else if (from.equals("我卖出的")){
                ivUserImg.setImageBitmap(winnerBm);
                tvPhoneTag.setText("买家手机");
                String winner_phone = MyUtil.getUserPhoneByID(ItemDetailsViewActivity.this, winner_id);
                tvPhone.setText(winner_phone);
            }

            //不通过原因
            String item_remark = cursor.getString(cursor.getColumnIndex("item_remark"));
            tv_no_pass_remark.setText(item_remark);

            //发布时间
            String add_time = cursor.getString(cursor.getColumnIndex("addtime"));
            tvOwnerAddTime.setText(add_time);
            //结束时间
            String end_time = cursor.getString(cursor.getColumnIndex("endtime"));
            tvEndTime.setText(end_time);
            tvOwnerEndTime.setText(end_time);

        }

    }

    @SuppressLint({"Range", "ClickableViewAccessibility"})
    private void initData() {
        item_id = Integer.parseInt(getIntent().getExtras().getString("item_id"));
        user_id = getIntent().getExtras().getInt("user_id");
//        Toast.makeText(this, item_id.toString(), Toast.LENGTH_SHORT).show();

        //根据拍卖品名称查找item表
        cursor = sqlite.selectItem("item_id", item_id.toString(), "item_id desc");

        //获取从哪个页面跳转过来的信标
        from = getIntent().getExtras().getString("from");

        //详情页滑动吸附
        sc_content.setOnTouchListener(new detailsScroll());

        //详情页不同来源显示不同内容
        //从首页跳转过来的用户
        if (from.equals("home")
                || from.equals("mineBidding")
        ) {
            //gone是隐藏且不占位
            ibtn_publish_again.setVisibility(View.GONE);
            rl_remark.setVisibility(View.GONE);
            rl_winner.setVisibility(View.GONE);
            llOnlyOwner.setVisibility(View.GONE);
        }
        //从发布跳转过来的用户
        else if (from.equals("publish")
                || from.equals("mineReview")
                || from.equals("mineClose")
//                || from.equals("mineBidding")
                || from.equals("我买到的")
                || from.equals("我卖出的")) {
            if (cursor != null && cursor.moveToFirst()) {
                String state = cursor.getString(cursor.getColumnIndex("state"));

                //详情页不同状态显示不同内容
                defaultState(state);

                //gone是隐藏且不占位
                if (from.equals("我买到的") || from.equals("我卖出的")) {
                    rl_phone.setVisibility(View.VISIBLE);
                } else {
                    rl_phone.setVisibility(View.GONE);
                }
                //隐藏底部竞价栏部分组件
                rlBid.setVisibility(View.GONE);
                rlEnterBid.setVisibility(View.GONE);

                //降低底部栏高度
                ViewGroup.LayoutParams vg = rl_bottom_nav.getLayoutParams();
                vg.width = ViewGroup.LayoutParams.MATCH_PARENT;
                //这里的60是实际的dp
                vg.height = MyUtil.dp2px(ItemDetailsViewActivity.this, 60);
            }
        }
    }

    //详情页不同状态显示不同内容
    @SuppressLint("Range")
    private void defaultState(String state) {
        UserDialog userDialog;
        tv_state.setVisibility(View.VISIBLE);
        llOnlyOwner.setVisibility(View.VISIBLE);
        ibtn_publish_again.setVisibility(View.GONE);
        rl_remark.setVisibility(View.GONE);
        rl_winner.setVisibility(View.GONE);
        ll_maxp_and_end.setVisibility(View.GONE);

        if (state.equals("已通过")) {
            rl_winner.setVisibility(View.VISIBLE);
            ll_maxp_and_end.setVisibility(View.VISIBLE);
            tv_state.setVisibility(View.GONE);
            tvFrontMaxPrice.setText("当前");
        } else {
            if (state.equals("不通过")) {
                String item_remark = cursor.getString(cursor.getColumnIndex("item_remark"));
                ibtn_publish_again.setVisibility(View.VISIBLE);
                rl_remark.setVisibility(View.VISIBLE);
                tv_state.setText(state);
                tv_state.setBackgroundResource(R.color.state_red);
                rl_bottom_nav.setBackgroundResource(R.color.state_red);
                //弹框
                userDialog = new UserDialog(ItemDetailsViewActivity.this, new UserDialog.OnCloseListener() {
                    @Override
                    public void onClick(Dialog dialog, boolean confirm) {
                        dialog.dismiss();
                    }
                });
                userDialog.setTitle("很遗憾，拍卖品审核不通过！").show();
                userDialog.setContent("审核意见：" + item_remark).show();
            } else if (state.equals("审核中")) {
                tv_state.setVisibility(View.VISIBLE);
                tv_state.setText(state);
                tv_state.setBackgroundResource(R.color.state_yellow);
                rl_bottom_nav.setBackgroundResource(R.color.state_yellow);
            } else if (state.equals("已结束")) {
                rl_winner.setVisibility(View.VISIBLE);
                ll_maxp_and_end.setVisibility(View.VISIBLE);
                tvFrontMaxPrice.setText("成交");
                tv_state.setVisibility(View.GONE);
                tvEndTime.setBackgroundResource(R.drawable.gray_button_nomal);
                rl_phone.setVisibility(View.VISIBLE);
            }
        }
    }

    private class detailsScroll implements View.OnTouchListener {
        @SuppressLint("ClickableViewAccessibility")
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            Boolean flag = false;
            switch (event.getAction()) {
                //按下
                case MotionEvent.ACTION_DOWN:
                    break;
                //滑动距离
                case MotionEvent.ACTION_MOVE:
                    //滑动超过item_image后自动吸附顶边
                    if (sc_content.getScrollY() >= (ivItemImg.getMeasuredHeight()) * 39 / 40
                    && sc_content.getScrollY() < (ivItemImg.getMeasuredHeight() * 81 / 80)) {
                        sc_content.scrollTo(0, ivItemImg.getBottom());
                    }else if (sc_content.getScrollY() >= (ivItemImg.getMeasuredHeight()) * 8 / 7){
                        sc_content.scrollTo(0, llOwner.getBottom());
                    }
                    break;
                //抬起
                case MotionEvent.ACTION_UP:
                    break;
            }
            return false;
        }
    }

    private void findViewBy() {
        tvBack = findViewById(R.id.tv_back);
        ibtn_publish_again = findViewById(R.id.ibtn_publish_again);

        sc_content = findViewById(R.id.sc_content);

        ivItemImg = findViewById(R.id.iv_item_img);
        ivOwnerImg = findViewById(R.id.iv_owner_img);
        ivWinnerImg = findViewById(R.id.iv_winner_img);
        ivUserImg = findViewById(R.id.iv_user_img);

        rl_phone = findViewById(R.id.rl_phone);
        rl_winner = findViewById(R.id.rl_winner);
        rl_remark = findViewById(R.id.rl_remark);

        tvOwnerName = findViewById(R.id.tv_owner_name);
        tvWinnerName = findViewById(R.id.tv_winner_name);
        tvItemName = findViewById(R.id.tv_item_name);
        tv_no_pass_remark = findViewById(R.id.tv_no_pass_remark);

        tvMarkupPrice = findViewById(R.id.tv_markup_price);
        tvItemDes = findViewById(R.id.tv_item_des);

        tvPhone = findViewById(R.id.tv_phone);
        tvPhoneTag = findViewById(R.id.tv_phone_tag);

        tv_state = findViewById(R.id.tv_state);
        ll_maxp_and_end = findViewById(R.id.ll_maxp_and_end);
        tvMaxPrice = findViewById(R.id.tv_max_price);
        tvFrontMaxPrice = findViewById(R.id.tv_front_max_price);
        tvEndTime = findViewById(R.id.tv_end_time);

        ibtnBidSubtract = findViewById(R.id.ibtn_bid_subtract);
        tvNewMaxPrice = findViewById(R.id.tv_new_max_price);
        ibtnBidAdd = findViewById(R.id.ibtn_bid_add);

        rlBid = findViewById(R.id.rl_bid);
        rlEnterBid = findViewById(R.id.rl_enter_bid);
        rl_bottom_nav = findViewById(R.id.rl_bottom_nav);

        llOwner = findViewById(R.id.ll_owner);
        llOnlyOwner = findViewById(R.id.ll_only_owner);
        tvOwnerInitPrice = findViewById(R.id.tv_owner_init_price);
        tvOwnerAddTime = findViewById(R.id.tv_owner_add_time);
        tvOwnerEndTime = findViewById(R.id.tv_owner_end_time);

    }

}